// pages/cashService/superAdmin/modeSelection/modeSelection.js
const { request } = require('../../../../utils/request');
const { formatDay } = require('../../../../utils/util');
const { imgPath } = require('../../../../utils/request');
const { encryptSM2 } = require('../../../../utils/sm-crypto');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgPath: imgPath,
    ifshowPicker: false,
    pickedStr: '', // yyyy-mm-dd
    pickedDate: null,
    currentDate: new Date().getTime(),  // 毫秒
    minDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return `${value}日`;
    },
    maxDate: new Date().getTime(),
    dateList: [],
    pageDateList: [],
    ifTriggered: false,

    ifShowSetting: false,
    showPwdDialog: false,
    oldPwd: '',
    pwd: '',
    pwd2: '',
    pwdInfo: '',
    btnDisable: true,
    captchaData: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '现金交款情况表'
    })
    this.fetchStartDate()
    let today = new Date()
    this.setData({
      minDate: new Date(today.getTime() - 24 * 60 * 60 * 1000).getTime(),
      maxDate: new Date(today.getTime() - 24 * 60 * 60 * 1000).getTime()
    })
  },
  fetchStartDate() {
    request('/smsk/wechat/report/startDate', 'GET', {}).then(res => {
      if (res.data.code == 0) { //yyyymmdd
        let temp = res.data.data.slice(0, 4) + '/' + res.data.data.slice(4, 6) + '/' + res.data.data.slice(6, 8)
        // 判断最早日期是否小于昨天
        let tempTime = new Date(temp).getTime() // 报表最早日
        console.log(tempTime)
        console.log(this.data.minDate)
        if (tempTime >= this.data.minDate) {
          tempTime = this.data.minDate
        }
        this.setData({
          minDate: tempTime,
          pickedStr: '',
          pickedDate: null,
        })
        this.fetchDateList()
      } else {
        console.log(res.data)
        wx.showToast({
          icon: 'none',
          title: res.data.message,
        })
      }
    })
  },
  fetchDateList: function () {
    let templist = []
    for (var i = this.data.minDate; i <= this.data.maxDate;) {
      templist.unshift(formatDay(i));
      i += 24 * 60 * 60 * 1000;
    }
    let tempP = [].concat(templist)
    this.setData({
      dateList: templist,
      pageDateList: tempP.splice(0, 15),
      ifTriggered: false
    })
  },
  fetchMore: function () {
    let start = this.data.pageDateList.length
    let tempDateList = [].concat(this.data.dateList)
    tempDateList = tempDateList.splice(start, 15)
    let temp = this.data.pageDateList.concat(tempDateList)
    this.setData({
      pageDateList: temp
    })
  },
  download: function (e) {
    let temp = e.currentTarget.dataset.date.replace(/-/g, '')
    const query = {
      startDate: temp,
      endDate: temp
    }
    request('/smsk/wechat/report/downloadCxbb', 'POST', query).then(res => {
      console.log(res.data)
      if (res.data.code == 0) {
        this.saveRespFile(res.data)
      } else {
        wx.showToast({
          icon: 'none',
          title: res.data.message,
        })
      }
    })
  },

  saveRespFile(response) {
    const filename = response.data.fileName;
    const _fsm = wx.getFileSystemManager()
    const filePath = `${wx.env.USER_DATA_PATH}/${filename}`
    _fsm.writeFile({
      filePath: filePath,
      data: response.data.content,
      encoding: 'base64',
      success(res) {
        console.log(res)
        const sysInfo = wx.getSystemInfoSync()
        console.log(sysInfo)
        // 导出
        if (sysInfo.platform.toLowerCase().indexOf('windows') >= 0) {
          // 电脑PC端导出
          wx.saveFileToDisk({
            filePath: filePath,
            success(res) {
              console.log(res)
              wx.showToast({
                title: '保存成功',
              })
            },
            fail(res) {
              console.error(res)
              wx.showToast({
                icon: 'error',
                title: '保存失败',
              })
            }
          })
        } else {
          // 手机端导出
          // 打开文档
          wx.openDocument({
            filePath: filePath,
            showMenu: true,
            success: function (res) {
              console.log('打开文档成功')
            },
            fail: console.error
          })
        }

      },
      fail(res) {
        console.error(res)
        if (res.errMsg.indexOf('locked')) {
          wx.showModal({
            title: '提示',
            content: '文档已打开，请先关闭',
          })
        }
      }
    })
  },

  showDatePicker() {
    this.setData({ ifshowPicker: true })
  },
  closePicker() {
    this.setData({ ifshowPicker: false })
  },
  onPickerConfirm(e) {
    let temp = []
    temp.push(formatDay(e.detail))
    this.setData({
      pickedDate: e.detail,
      pickedStr: formatDay(e.detail),
      ifshowPicker: false,
      pageDateList: temp
    })
  },
  cleanDate() {
    let tempP = [].concat(this.data.dateList)
    this.setData({
      pickedDate: null,
      pickedStr: '',
      pageDateList: tempP.splice(0, 15)
    })
  },

  // 刷新列表
  refreshList() {
    this.fetchStartDate()
  },

  closeSetting() {
    this.setData({ ifShowSetting: false })
  },
  showSetting() {
    this.setData({ ifShowSetting: !this.data.ifShowSetting })
  },

  showPwdChange() {
    this.setData({
      ifShowSetting: !this.data.ifShowSetting,
      showPwdDialog: true,
      oldPwd: '',
      pwd: '',
      pwd2: ''
    })
    // 获取
    this.fetchCaptcha()
  },
  onClose() {
    this.setData({ showPwdDialog: false })
  },
  checkPwd() {
    this.setData({ pwdInfo: '', btnDisable: true })
    if (this.data.pwd && this.data.pwd2) {
      if (this.data.pwd != this.data.pwd2) {
        this.setData({ pwdInfo: '两次输入密码不同' })
      } else if (this.data.oldPwd) {
        this.setData({ btnDisable: false })
      }
    }
  },
  changePwd() {
    if (this.data.btnDisable) {
      return
    }
    let query = {
      oldpasswd: encryptSM2(this.data.oldPwd, this.data.captchaData.publicKey),
      newpasswd: encryptSM2(this.data.pwd, this.data.captchaData.publicKey),
      captchaId: this.data.captchaData.captchaId,
      encrypted: true
    }
    request('/smsk/wechat/auth/passwd', 'POST', query).then(res => {
      // console.log(res.data) 
      this.fetchCaptcha()
      if (res.data.code == 0) {
        wx.showToast({
          title: '修改成功',
          icon: 'success'
        })
        this.setData({
          showPwdDialog: false,
          oldPwd: '',
          pwd: '',
          pwd2: ''
        })
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        })
      }
    })
  },
  fetchCaptcha() {
    request('/smsk/wechat/auth/captchaw150h30', 'GET').then(res => {
      this.setData({
        captchaData: res.data.data
      })
    })
  }

})